﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
using System.Globalization;

namespace MulticastTV
{

    /// <summary>
    /// Settings form
    /// TODO: Use MLmessages instead of hardcoded translations.
    /// </summary>
    public partial class PreferencesForm : Form
    {
        private Form1 parent;
        string path;
        List<string> interfacenames;
        string selectedinterface;
        byte[] start;
        byte[] stop;
        int port;
        char[] colondelimiter = { ':' };
        Scanner scanner;
        DataGridView chtable = new DataGridView();
        DataTable ksd;
        static string AppPath = System.Windows.Forms.Application.CommonAppDataPath;
       
        bool savechannels = false;
        bool formloaded = false;
        bool error = false;
        bool vlcInitNeeded = false;
        bool restartNeeded = false;

        /// <summary>
        /// Constructor
        /// </summary>
        public PreferencesForm(Form1 parentForm, string pth, DataGridView ct)
        {
            InitializeComponent();
            parent = parentForm;
            chtable = ct;
            path = pth;
       }

        private void Form3_Load(object sender, EventArgs e)
        {
            load();
        }

        /// <summary>
        /// Update GUI with settings
        /// </summary>
        private void load()
        {
            Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\", true);

            // Fill shortcuts table
            populatekeyShortCuts();

            if ((string)key.GetValue("MulticastTV") != null)
            {
                checkBox1.CheckState = CheckState.Checked;
            }
            textBox1.Text = Properties.Settings.Default.RecFolder;
            dataGridView1.Columns[0].DataPropertyName = "Ip";
            dataGridView1.Columns[1].DataPropertyName = "Chan";
            dataGridView1.Columns[2].DataPropertyName = "Name";
            dataGridView1.Columns[3].DataPropertyName = "Group";
            dataGridView1.Columns[4].DataPropertyName = "Audio";
            dataGridView1.Columns[5].DataPropertyName = "Fav";
            dataGridView1.Columns[6].DataPropertyName = "Skip";
            dataGridView1.Columns[7].DataPropertyName = "Logo";
            dataGridView1.Columns[7].Visible = false;
            dataGridView1.Columns[8].DataPropertyName = "Locked";

            bindingSource1.DataSource = ChannelTable.menu.Tables["Menu"];
            dataGridView1.DataSource = bindingSource1;
            
            // show all channels
            if (bindingSource1.Filter != "")
                bindingSource1.Filter = "";

            // splitbutton
            splitButton1.ContextMenuStrip = contextMenuStrip1;

            //  TODO tool tips
            if (Properties.Settings.Default.language == "Slovenian")
                dataGridView1.Columns[0].ToolTipText = "Dvojni klik na ip celico za predogled";
            else
                dataGridView1.Columns[0].ToolTipText = "Double click on ip cell to open preview window.";

            ToolTip recoffset = new ToolTip();
            if (Properties.Settings.Default.language == "Slovenian")
                recoffset.SetToolTip(label20, "Zamik snemanja, ko je snemanje dodano iz epg-ja.");
            else
                recoffset.SetToolTip(label20, "Recording offset, when recording schedule added from TV schedule window.");

            if (Properties.Settings.Default.language == "Slovenian")
                toolTip1.SetToolTip(checkBox79, "Obkljukajte index ali ip, če izbor mrežne kartice ne deluje.");
            else
                toolTip1.SetToolTip(checkBox79, "");

            if (Properties.Settings.Default.language == "Slovenian")
                toolTip1.SetToolTip(checkBox4, "Omogoči Osd");
            else
                toolTip1.SetToolTip(checkBox4, "Enable Osd");
            
            Interfaces interfaces = new Interfaces();
            interfacenames = interfaces.getNames();
  
            // Clear combobox if not empty
            if (comboBox1.Items.Count>0)
                comboBox1.Items.Clear();

            selectedinterface = Properties.Settings.Default.InterfaceName;
            bool intfIsListed = false;

            // Populate combobox with names
            foreach (string iname in interfacenames)
            {
                comboBox1.Items.Add(iname);
                if (iname == selectedinterface)
                    intfIsListed = true;
            }

            try
            {
                if (selectedinterface.Length == 0 || !intfIsListed)
                    comboBox1.SelectedIndex = 0;
                else
                    comboBox1.SelectedItem = selectedinterface;
            }
            catch { }

            // Set initial ip fields to ip of first item in favourites
            try
            {
                IPAddress loadStart = IPAddress.Parse(ChannelTable.menu.Tables["Menu"].Rows[0][0].ToString().Split(colondelimiter)[0]);
                port = int.Parse(ChannelTable.menu.Tables["Menu"].Rows[0][0].ToString().Split(colondelimiter)[1]);
                start = loadStart.GetAddressBytes();
                stop = loadStart.GetAddressBytes();
                stop[3] = 255;
                ipAddressControl1.SetAddressBytes(start);
                ipAddressControl2.SetAddressBytes(stop);
                numericUpDown3.Value = port;
            }
            catch { }

            // Let's populate remote settings
            if (Properties.Settings.Default.VlcIp.Length > 0)
            {
                IPAddress vlcip = IPAddress.Parse(Properties.Settings.Default.VlcIp);
                ipAddressControl3.SetAddressBytes(vlcip.GetAddressBytes());
            }
            if (Properties.Settings.Default.DestIp.Length > 0)
            {
                IPAddress destip = IPAddress.Parse(Properties.Settings.Default.DestIp);
                ipAddressControl4.SetAddressBytes(destip.GetAddressBytes());
            }

            //Vlc port
            numericUpDown4.Value = Properties.Settings.Default.VlcPort;
            //Rec offset
            numericUpDown6.Value = Properties.Settings.Default.RecStartOffset;
            numericUpDown7.Value = Properties.Settings.Default.RecStopOffset;
            //Udp cache
            numericUpDown8.Value = Properties.Settings.Default.UdpCache;

            // generate uniqe vlm name with rnd
            if (Properties.Settings.Default.VlmName.Length == 0)
            {
                Random random = new Random();
                int num = random.Next(1000, 9999);
                string vlmrand = "multicastv" + num.ToString();
                Properties.Settings.Default.VlmName = vlmrand;
            }

            textBox2.Text = Properties.Settings.Default.VlmName;
            numericUpDown5.Value = Properties.Settings.Default.DestPort;

            //Language combobox !!! HARDCODED TRANSLATION ! Use MLmessages.resx!
            comboBox3.Items.Add("English");
            comboBox3.Items.Add("Slovenian");
            //Show selected
            if (Properties.Settings.Default.language == "English" || Properties.Settings.Default.language == "default")
            {
                comboBox3.SelectedIndex = comboBox3.Items.IndexOf("English");
            }
            if (Properties.Settings.Default.language == "Slovenian")
            {
                comboBox3.SelectedIndex = comboBox3.Items.IndexOf("Slovenian");
            }

            //Font colors
            panel1.BackColor = Properties.Settings.Default.OSDcolor;
            panel3.BackColor = Properties.Settings.Default.EPGBackColor;
            panel4.BackColor = Properties.Settings.Default.EPGBackColor;
            panel5.BackColor = Properties.Settings.Default.TableBackColor_v2;
            label19.ForeColor = Properties.Settings.Default.EPGTextColor;
            label26.ForeColor = Properties.Settings.Default.EPGHighTextColor;
            label10.ForeColor = Properties.Settings.Default.TableTextColor;
            panel7.BackColor = Properties.Settings.Default.EPGBackColor;
            panel6.BackColor = Properties.Settings.Default.TableBackColor_v2;
            panel9.BackColor = Properties.Settings.Default.SideBarBackColor;
            panel10.BackColor = Properties.Settings.Default.SideBarBackColor;
            label37.ForeColor = Properties.Settings.Default.SidebarFontColor;

            //Skip loop filter
            numericUpDown9.Value = Properties.Settings.Default.VideoSkipLoopFilterV2;
           
            // Hardware yuv
            if (Properties.Settings.Default.VideoHardwareYuv)
                checkBox3.CheckState = CheckState.Checked;
            else
                checkBox3.CheckState = CheckState.Unchecked;
           
            //Deinterlace mode
            comboBox4.SelectedIndex= comboBox4.Items.IndexOf(Properties.Settings.Default.VideoDeinterlaceV4);
            if (comboBox4.SelectedIndex == -1)
                comboBox4.SelectedIndex = 0;

            // Show osd
            if (Properties.Settings.Default.OSDshow)
                checkBox4.CheckState = CheckState.Checked;
            else
                checkBox4.CheckState = CheckState.Unchecked;

            // Mouse clicks
            if (Properties.Settings.Default.MouseSetChannel == 1)
                comboBox5.SelectedIndex = 0;
            if (Properties.Settings.Default.MouseSetChannel == 2)
                comboBox5.SelectedIndex = 1;

            //  Mouse wheel swap
            if (Properties.Settings.Default.MouseSwap == true)
                checkBox6.CheckState = CheckState.Checked;
            else
                checkBox6.CheckState = CheckState.Unchecked;

            // Epg pop-up
            if (Properties.Settings.Default.EpgFs)
                checkBox7.CheckState = CheckState.Checked;
            else
                checkBox7.CheckState = CheckState.Unchecked;
            
            // Vista hack
            uncheckCardSelectionCB();
            if (Properties.Settings.Default.VistaHack == 0)
                checkBox79.CheckState = CheckState.Checked;
            else if (Properties.Settings.Default.VistaHack == 1)
                checkBox80.CheckState = CheckState.Checked;
            else if (Properties.Settings.Default.VistaHack == 2)
                checkBox81.CheckState = CheckState.Checked;

            // Recording format
            if (Properties.Settings.Default.RecordingFormat == "ts")
            {
                comboBox8.SelectedIndex = 0;
            }
            else if (Properties.Settings.Default.RecordingFormat == "ps")
            {
                comboBox8.SelectedIndex = 1;
            }
            if (Properties.Settings.Default.RecRaw == true)
                checkBox2.CheckState = CheckState.Checked;
            else
                checkBox2.CheckState = CheckState.Unchecked;

            // Video out 
            if (Properties.Settings.Default.VideoOutV3 == "Directx")
            {
                comboBox6.SelectedIndex = 0;
            }
            else if (Properties.Settings.Default.VideoOutV3 == "Direct3d")
            {
                comboBox6.SelectedIndex = 1;
            }
            else if (Properties.Settings.Default.VideoOutV3 == "OpenGL")
            {
                comboBox6.SelectedIndex = 2;
            }
            else
            {
                 Properties.Settings.Default.VideoOutV3 = "Direct3d";
                 comboBox6.SelectedIndex = 1;
            }

            //texture filter d3d
            if (Properties.Settings.Default.VideoD3dTextureFilter == "1")
                comboBox14.SelectedIndex = 0;
            else if (Properties.Settings.Default.VideoD3dTextureFilter == "2")
                comboBox14.SelectedIndex = 1;
            else
                 comboBox14.SelectedIndex = 1;

            // Audio settings
            if (Properties.Settings.Default.AudioAPI == "default")
                comboBox7.SelectedIndex = 0;
            else if (Properties.Settings.Default.AudioAPI == "waveout")
                comboBox7.SelectedIndex = 1;
            if (Properties.Settings.Default.AudioDolbyProLogic == "auto")
                comboBox9.SelectedIndex = 0;
            else if (Properties.Settings.Default.AudioDolbyProLogic == "on")
                comboBox9.SelectedIndex = 1;
            else if (Properties.Settings.Default.AudioDolbyProLogic == "off")
                comboBox9.SelectedIndex = 2;
            if (Properties.Settings.Default.AudioNormalize == true)
                checkBox12.CheckState = CheckState.Checked;
            else
                checkBox12.CheckState = CheckState.Unchecked;
            if (Properties.Settings.Default.AudioSPDIFPass == true)
                checkBox11.CheckState = CheckState.Checked;
            else
                checkBox11.CheckState = CheckState.Unchecked;
            numericUpDown10.Value = Properties.Settings.Default.AudioSync;

            // Remote control
            if (Properties.Settings.Default.RemoteMode2)
                checkBox13.CheckState = CheckState.Checked;
            else
                checkBox13.CheckState = CheckState.Unchecked;

            // Screen saver
            if (Properties.Settings.Default.ScreenSaver)
                checkBox14.CheckState = CheckState.Checked;
            else
                checkBox14.CheckState = CheckState.Unchecked;

            // Unicast server
            if (Properties.Settings.Default.UnicastServer == "vlc")
            {
                checkBox15.CheckState = CheckState.Checked;
                checkBox16.CheckState = CheckState.Unchecked;
            }
            else if (Properties.Settings.Default.UnicastServer == "udprelay")
            {
                checkBox16.CheckState = CheckState.Checked;
                checkBox15.CheckState = CheckState.Unchecked;
            }

            // Per channel settings
            if (Properties.Settings.Default.PerChEnabled)
                checkBox8.CheckState = CheckState.Checked;
            else
                checkBox8.CheckState = CheckState.Unchecked;
            if (Properties.Settings.Default.PerChAspectRatio)
                checkBox17.CheckState = CheckState.Checked;
            else
                checkBox17.CheckState = CheckState.Unchecked;
            if (Properties.Settings.Default.PerChZoomRatio)
                checkBox18.CheckState = CheckState.Checked;
            else
                checkBox18.CheckState = CheckState.Unchecked;
            if (Properties.Settings.Default.PerChVolume)
                checkBox21.CheckState = CheckState.Checked;
            else
                checkBox21.CheckState = CheckState.Unchecked;
            if (Properties.Settings.Default.PerChDeinterlace)
                checkBox22.CheckState = CheckState.Checked;
            else
                checkBox22.CheckState = CheckState.Unchecked;
            if (Properties.Settings.Default.PerChAudioPid)
                checkBox19.CheckState = CheckState.Checked;
            else
                checkBox19.CheckState = CheckState.Unchecked;
            if (Properties.Settings.Default.PerChSubtitlePid)
                checkBox20.CheckState = CheckState.Checked;
            else
                checkBox20.CheckState = CheckState.Unchecked;

            // audio subs language
            textBox3.Text = Properties.Settings.Default.AudioPrefLang;
            textBox4.Text = Properties.Settings.Default.SubtitlePrefLang;
            // Subs verttical position
            numericUpDown1.Value = Properties.Settings.Default.SubtitleYPos;

            // last selected channel
            if (Properties.Settings.Default.RememberLastSelectedChan)
                checkBox24.CheckState = CheckState.Checked;
            else
                checkBox24.CheckState = CheckState.Unchecked;

            // mouse for volume
            if (Properties.Settings.Default.MouseForVolume)
                checkBox9.CheckState = CheckState.Checked;
            else
                checkBox9.CheckState = CheckState.Unchecked;

            // additional info
            if (Properties.Settings.Default.ShowStatusStripDetails)
                checkBox25.CheckState = CheckState.Checked;
            else
                checkBox25.CheckState = CheckState.Unchecked;

            // password
            PasswordEncription.decrypt();
            maskedTextBox1.Text = PasswordEncription.Password;

            // Plugins
            // Add all plugins
            foreach (Types.AvailablePlugin pluginOn in GlobalP.Plugins.AvailablePlugins)
            {
                comboBox2.Items.Add(pluginOn.Instance.Name);
                if (pluginOn.Instance.Name == Properties.Settings.Default.EPGPlugin)
                { 
                    //select that plugin
                    comboBox2.SelectedIndex = comboBox2.Items.IndexOf(pluginOn.Instance.Name);
                }
            }
            recOptions();

            // Plugin checkbox
            if (Properties.Settings.Default.EnableEpgplugin && comboBox2.Items.Count > 0)
            {
                checkBox5.CheckState = CheckState.Checked;
            }
            else
            {
                // No dll plugin found so we also disable pop-up
                checkBox5.CheckState = CheckState.Unchecked;
                Properties.Settings.Default.EpgFs = false;
                checkBox7.CheckState = CheckState.Unchecked;
            }

            // DISABLE STUFFF always at the end
            if (comboBox2.SelectedIndex == -1)
            {
                button14.Enabled = false;
                checkBox5.CheckState = CheckState.Unchecked;
                checkBox7.CheckState = CheckState.Unchecked;
            }
            else
            {
                button14.Enabled = true;
            }
            
            formloaded = true;
        }


        /// <summary>
        /// Update GUI after reloading settings
        /// </summary>
        private void reload()
        {
            //default rec folder
            string recfolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\MulticastTV";
            Properties.Settings.Default.RecFolder = recfolder;
            
            //default interface
            Interfaces intf = new Interfaces();
            try
            {
                string name = intf.getNames()[0];
                string ip = intf.getIpFromName(name);
                Properties.Settings.Default.InterfaceName = name;
                Globals.interfaceip = ip;
            }
            catch { MessageBox.Show("Can't get local ip. "); Globals.interfaceip = ""; return; }

            comboBox3.Items.Clear();
            comboBox2.Items.Clear();
            load();
        }

        private void button1_Click(object sender, EventArgs e)
        {
              if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                 // select recording path
                 textBox1.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        /// <summary>
        /// Write to registry (start minimized)
        /// </summary>
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            if (checkBox1.CheckState==CheckState.Checked)
                key.SetValue("MulticastTV", Application.ExecutablePath.ToString()+" min");
            else
                key.DeleteValue("MulticastTV", false);
        }

        public delegate void delegateParentThread();
        /// <summary>
        /// Start scanning
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
              IPAddress ipstart = new IPAddress(ipAddressControl1.GetAddressBytes());
            IPAddress ipstop = new IPAddress(ipAddressControl2.GetAddressBytes());
            if (ipstart.ToString() == "0.0.0.0" || ipstop.ToString() == "0.0.0.0")
                return;

            parent.Invoke(new delegateParentThread(parent.vlcStop));
            button2.Enabled = false;
            button3.Enabled = true;
            scanner = new Scanner(button2,button3,progressBar1,label9,label18,dataGridView1);
            int timeout = (int)numericUpDown2.Value;
            port = (int)numericUpDown3.Value;
            scanner.StartScann(ipstart, ipstop, port, timeout);
        }

        /// <summary>
        /// Delete row
        /// </summary>
        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
                try
                {
                    foreach (DataGridViewRow drw in dataGridView1.SelectedRows)
                    {
                         if (drw.IsNewRow != true)
                        dataGridView1.Rows.Remove(drw);
                   }
                }
                catch { }

            // move up down
            if (e.KeyCode == Keys.Down && dataGridView1.SelectedRows.Count > 0 )
            {
                swapWithRow(true);
                e.Handled = true;
            }
            if (e.KeyCode == Keys.Up && dataGridView1.SelectedRows.Count > 0)
            {
                swapWithRow(false);
                e.Handled = true;
            }

            // export groupes
            if (e.KeyCode == Keys.F11)
            {
                ExportGroups eg = new ExportGroups();
                eg.Start();
            }
            // export to vlm/m3u
            if (e.KeyCode == Keys.F10)
            {
                VLMExportForm ve = new VLMExportForm();
                ve.Show();
                this.TopMost = false;
            }
            //export to names
            if (e.KeyCode == Keys.F9)
            {
                ExportNames.Start(Properties.Settings.Default.RecFolder+@"\imena.txt");
            }
        }

        /// <summary>
        /// Stop scanning
        /// </summary>
        private void button3_Click(object sender, EventArgs e)
        {
            button2.Enabled = true;
            button3.Enabled = false;
            scanner.stopScann();
        }

        /// <summary>
        /// Channel preview
        /// </summary>
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0) 
            {
                string ip = (string)dataGridView1.CurrentRow.Cells[0].Value;
                string name = (string)dataGridView1.CurrentRow.Cells[2].Value;
                int num = (int)dataGridView1.CurrentRow.Cells[1].Value;
                bool skip = (bool)dataGridView1.CurrentRow.Cells[6].Value;
                bool locked = (bool)dataGridView1.CurrentRow.Cells[8].Value;
                if (locked)
                {
                    return;
                }
                ChannelData cd = new ChannelData(ip, name, num, "@All", locked, skip);
                VlcNewWindowForm newplayer = new VlcNewWindowForm(cd,parent);
                newplayer.Show();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            saveSettings();
            parent.Invoke(new delegateParentThread(parent.sidebarcolors));
        }
       
        private void button6_Click(object sender, EventArgs e)
        {
            UnicastConntest ctest = new UnicastConntest();
            ctest.check(new IPAddress(ipAddressControl3.GetAddressBytes()).ToString(), (int)numericUpDown4.Value, label16, false);
        }

        /// <summary>
        /// Save settings
        /// </summary>
        private void saveSettings()
        {
            try
            {
                parent.populateFavmenu("name");
                updateShortcuts();
                Properties.Settings.Default.RecFolder = textBox1.Text;
                Properties.Settings.Default.InterfaceName = comboBox1.SelectedItem.ToString();
                Properties.Settings.Default.DestPort = (int)numericUpDown5.Value;
                Properties.Settings.Default.VlcPort = (int)numericUpDown4.Value;
                Properties.Settings.Default.VlcIp = new IPAddress(ipAddressControl3.GetAddressBytes()).ToString();
                Properties.Settings.Default.DestIp = new IPAddress(ipAddressControl4.GetAddressBytes()).ToString();
                Properties.Settings.Default.RecStartOffset = (int)numericUpDown6.Value;
                Properties.Settings.Default.RecStopOffset = (int)numericUpDown7.Value;
                Properties.Settings.Default.UdpCache = (int)numericUpDown8.Value;
                Properties.Settings.Default.language = comboBox3.SelectedItem.ToString();
                Properties.Settings.Default.VideoSkipLoopFilterV2 = (int)numericUpDown9.Value;
                if (comboBox4.SelectedIndex == -1 || comboBox4.SelectedIndex == 0)
                    Properties.Settings.Default.VideoDeinterlaceV4 = "";
                else
                    Properties.Settings.Default.VideoDeinterlaceV4 = comboBox4.SelectedItem.ToString();
               
                Properties.Settings.Default.VideoOutV3 = comboBox6.SelectedItem.ToString();
                if (comboBox4.SelectedIndex == 0)
                {
                    parent.deinterlaceToolStripMenuItem1.CheckState = CheckState.Unchecked;
                }
                else
                {
                    parent.deinterlaceToolStripMenuItem1.CheckState = CheckState.Checked;
                }

                if (checkBox3.CheckState == CheckState.Checked)
                    Properties.Settings.Default.VideoHardwareYuv = true;
                else
                    Properties.Settings.Default.VideoHardwareYuv = false;
                if (checkBox4.CheckState == CheckState.Checked)
                    Properties.Settings.Default.OSDshow = true;
                else
                    Properties.Settings.Default.OSDshow = false;

                if (comboBox5.SelectedIndex == 0)
                    Properties.Settings.Default.MouseSetChannel = 1;
                else
                    Properties.Settings.Default.MouseSetChannel = 2;

                if (checkBox6.CheckState == CheckState.Checked)
                    Properties.Settings.Default.MouseSwap = true;
                else
                    Properties.Settings.Default.MouseSwap = false;
                if (checkBox7.CheckState == CheckState.Checked)
                    Properties.Settings.Default.EpgFs = true;
                else
                    Properties.Settings.Default.EpgFs = false;
                if (checkBox79.CheckState == CheckState.Checked)
                {
                    Globals.determineInterfaceByIndex = (StandBy.isVista64() || StandBy.runingOnWin7());
                    Properties.Settings.Default.VistaHack = 0;
                }
                else if (checkBox80.CheckState == CheckState.Checked)
                {
                    Properties.Settings.Default.VistaHack = 1;
                    Globals.determineInterfaceByIndex = false;
                }
                else if (checkBox81.CheckState == CheckState.Checked)
                {
                    Properties.Settings.Default.VistaHack = 2;
                    Globals.determineInterfaceByIndex = true;
                }

                //texture filter
                if (comboBox14.SelectedIndex == 0)
                    Properties.Settings.Default.VideoD3dTextureFilter = "1";
                else if (comboBox14.SelectedIndex == 1)
                    Properties.Settings.Default.VideoD3dTextureFilter = "2";
                else
                    Properties.Settings.Default.VideoD3dTextureFilter = "2";

                ////audio settings
                if (comboBox7.SelectedIndex == 0)
                    Properties.Settings.Default.AudioAPI = "default";
                else if (comboBox7.SelectedIndex == 1)
                    Properties.Settings.Default.AudioAPI = "waveout";
                if (comboBox9.SelectedIndex == 0)
                    Properties.Settings.Default.AudioDolbyProLogic = "auto";
                else if (comboBox9.SelectedIndex == 1)
                    Properties.Settings.Default.AudioDolbyProLogic = "on";
                else if (comboBox9.SelectedIndex == 2)
                    Properties.Settings.Default.AudioDolbyProLogic = "off";
                if (checkBox12.CheckState == CheckState.Checked)
                    Properties.Settings.Default.AudioNormalize = true;
                else
                    Properties.Settings.Default.AudioNormalize = false;
                if (checkBox11.CheckState == CheckState.Checked)
                    Properties.Settings.Default.AudioSPDIFPass = true;
                else
                    Properties.Settings.Default.AudioSPDIFPass = false;
                Properties.Settings.Default.AudioSync = (int)numericUpDown10.Value;

                //remote control
               if (checkBox13.CheckState == CheckState.Checked)
                    Properties.Settings.Default.RemoteMode2 = true;
                else
                    Properties.Settings.Default.RemoteMode2 = false;
            
                //screen saver
                if (checkBox14.CheckState == CheckState.Checked)
                    Properties.Settings.Default.ScreenSaver = true;
                else
                    Properties.Settings.Default.ScreenSaver = false;

                if (Properties.Settings.Default.ScreenSaver)
                {
                    parent.Invoke(new delegateParentThread(parent.preventScreenSaver));
                }
                else
                {
                    parent.Invoke(new delegateParentThread(parent.enableScreenSaver));
                }
                
                // unicast server
                if (checkBox15.CheckState == CheckState.Checked)
                    Properties.Settings.Default.UnicastServer = "vlc";
                else if (checkBox16.CheckState == CheckState.Checked)
                    Properties.Settings.Default.UnicastServer = "udprelay"; 

                // recording format
                if (comboBox8.SelectedIndex == 0)
                    Properties.Settings.Default.RecordingFormat = "ts";
                else if (comboBox8.SelectedIndex == 1)
                    Properties.Settings.Default.RecordingFormat = "ps";

                if (checkBox2.CheckState == CheckState.Checked)
                    Properties.Settings.Default.RecRaw = true;
                else
                    Properties.Settings.Default.RecRaw = false;

                // culture info
                if (Properties.Settings.Default.language == "Slovenian")
                    //sl-SI
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("sl-SI");
                else
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("");
                  
                // per channel settings
                if (checkBox8.CheckState == CheckState.Checked)
                    Properties.Settings.Default.PerChEnabled = true;
                else
                    Properties.Settings.Default.PerChEnabled = false;
                if (checkBox17.CheckState == CheckState.Checked)
                    Properties.Settings.Default.PerChAspectRatio = true;
                else
                    Properties.Settings.Default.PerChAspectRatio = false;
                if (checkBox18.CheckState == CheckState.Checked)
                    Properties.Settings.Default.PerChZoomRatio = true;
                else
                    Properties.Settings.Default.PerChZoomRatio = false;
                if (checkBox21.CheckState == CheckState.Checked)
                    Properties.Settings.Default.PerChVolume = true;
                else
                    Properties.Settings.Default.PerChVolume = false;
                if (checkBox22.CheckState == CheckState.Checked)
                    Properties.Settings.Default.PerChDeinterlace = true;
                else
                    Properties.Settings.Default.PerChDeinterlace = false;
                if (checkBox19.CheckState == CheckState.Checked)
                    Properties.Settings.Default.PerChAudioPid = true;
                else
                    Properties.Settings.Default.PerChAudioPid = false;
                if (checkBox20.CheckState == CheckState.Checked)
                    Properties.Settings.Default.PerChSubtitlePid = true;
                else
                    Properties.Settings.Default.PerChSubtitlePid = false;

                // audio, sub lang
                Properties.Settings.Default.AudioPrefLang = textBox3.Text;
                Properties.Settings.Default.SubtitlePrefLang = textBox4.Text;

                // subs position
                Properties.Settings.Default.SubtitleYPos =  (int)numericUpDown1.Value;                

                // remember last chan
                if (checkBox24.CheckState == CheckState.Checked)
                    Properties.Settings.Default.RememberLastSelectedChan = true;
                else
                    Properties.Settings.Default.RememberLastSelectedChan = false;

                // mouse for volume
                if (checkBox9.CheckState == CheckState.Checked)
                    Properties.Settings.Default.MouseForVolume = true;
                else
                    Properties.Settings.Default.MouseForVolume = false;

                // aditional info
                if (checkBox25.CheckState == CheckState.Checked)
                    Properties.Settings.Default.ShowStatusStripDetails = true;
                else
                    Properties.Settings.Default.ShowStatusStripDetails = false;

                // plugins
                // Notify that this plugin is locked to one langue.
                if (checkBox5.CheckState == CheckState.Checked && comboBox2.SelectedIndex != -1)
                {
                    Types.AvailablePlugin selectedPlugin = GlobalP.Plugins.AvailablePlugins.Find((string)comboBox2.SelectedItem);
                    if (selectedPlugin != null)
                    {

                        if (Thread.CurrentThread.CurrentUICulture.Name.ToLower() == selectedPlugin.Instance.LockedToUserInterfaceLangue.ToLower() || selectedPlugin.Instance.LockedToUserInterfaceLangue == "")
                        {
                            Properties.Settings.Default.EnableEpgplugin = true;
                            Properties.Settings.Default.EPGPlugin = selectedPlugin.Instance.Name;
                        }
                        else
                        {
                            // if not correct language, disable epg plugin.
                            MessageBox.Show("This plugin is locked to specific user interface language");
                            Properties.Settings.Default.EnableEpgplugin = false;
                            Properties.Settings.Default.EpgFs = false;
                            Properties.Settings.Default.EPGPlugin = "";
                        }
                    }
                    else
                    {
                        // Should never happened.
                        Properties.Settings.Default.EnableEpgplugin = false;
                        Properties.Settings.Default.EpgFs = false;
                        Properties.Settings.Default.EPGPlugin = "";
                    }
                }
                // Disable epg.
                else
                {
                    Properties.Settings.Default.EnableEpgplugin = false;
                    Properties.Settings.Default.EpgFs = false;
                    Properties.Settings.Default.EPGPlugin = "";
                }

                // Update epg dictionary.
                pluginNames.loadNames(true); //update
                // Save current table to xml. Name is name of the plugin.
                pluginNames.savePluginNames(); //save to xml

                getInterfaceIpFromName();

                // Update index.
                Interfaces intfi = new Interfaces();
                Globals.interfaceindex = intfi.getIndexFromName(Properties.Settings.Default.InterfaceName).ToString();

                Properties.Settings.Default.Save();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + e.StackTrace);
                error = true;
                this.Close();
            }

            // Reset vlc instance if needed.
            if (vlcInitNeeded)
            {
                parent.Invoke(new delegateParentThread(parent.vlcStop));
                parent.Invoke(new delegateParentThread(parent.vlcDispose));
            }

            if (restartNeeded)
            {
                MessageBox.Show(MLmessages.RestartNeeded);
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            saveSettings();
            this.Close();
        }

        private void getInterfaceIpFromName() {
             
             try 
             {
                Interfaces intf = new Interfaces();
                Globals.interfaceip = intf.getIpFromName(Properties.Settings.Default.InterfaceName);
             }
             catch { }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            
            webBrowser1.Navigate("http://"+new IPAddress(ipAddressControl3.GetAddressBytes()).ToString()+":"+numericUpDown4.Value.ToString()+"/vlm.html");
        }

        private void button10_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button11_Click(object sender, EventArgs e)
        {
            openFileDialog1.CheckFileExists = true;
            openFileDialog1.Filter = "atvlist, m3u, xls (*.atvlist;*.m3u;*.xls)|*.ATVLIST;*.M3U;*.XLS";
            openFileDialog1.FileName = "";
            openFileDialog1.InitialDirectory = path + @"\import\";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                PreserveFavourites pf = new PreserveFavourites(AppPath);
                pf.saveBeforeImporting();

                StandBy.fillChannelTable(openFileDialog1.FileName);
                pf.restoreAfterImporting();
            }
            savechannels = true;
        }


        /// <summary>
        /// Osd color
        /// </summary>
        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            colorDialog1.Color = panel1.BackColor;
            if (colorDialog1.ShowDialog() != DialogResult.Cancel)
            {
                panel1.BackColor = colorDialog1.Color;
                Properties.Settings.Default.OSDcolor = colorDialog1.Color;
            }
        }

        /// <summary>
        /// EPG backcolor
        /// </summary>
        private void panel3_MouseDown(object sender, MouseEventArgs e)
        {
            colorDialog1.Color = panel3.BackColor;
            if (colorDialog1.ShowDialog() != DialogResult.Cancel)
            {
                panel3.BackColor = colorDialog1.Color;
                panel4.BackColor = colorDialog1.Color;
                panel7.BackColor = colorDialog1.Color;
                Properties.Settings.Default.EPGBackColor = colorDialog1.Color;
            }
        }

        /// <summary>
        /// EPG text
        /// </summary>
        private void panel4_MouseDown(object sender, MouseEventArgs e)
        {
            fontDialog1.ShowColor = true;
            fontDialog1.Color = label19.ForeColor;
            fontDialog1.Font = Properties.Settings.Default.EPGFont;
            //fontDialog1.Color = Color.Blue;
            if (fontDialog1.ShowDialog() != System.Windows.Forms.DialogResult.Cancel)
            {
                panel4.BackColor = panel3.BackColor;
                label19.ForeColor = fontDialog1.Color;
                Properties.Settings.Default.EPGTextColor=fontDialog1.Color;
                Properties.Settings.Default.EPGFont = fontDialog1.Font;
            }
        }

        /// <summary>
        /// Table background
        /// </summary>
        private void panel5_MouseDown(object sender, MouseEventArgs e)
        {
            colorDialog1.Color = panel5.BackColor;
            if (colorDialog1.ShowDialog() != DialogResult.Cancel)
            {
                panel5.BackColor = colorDialog1.Color;
                panel6.BackColor = colorDialog1.Color;
                Properties.Settings.Default.TableBackColor_v2=colorDialog1.Color;
            }
        }

        /// <summary>
        /// Table text
        /// </summary>
        private void panel6_MouseDown(object sender, MouseEventArgs e)
        {
            fontDialog1.ShowColor = true;
            fontDialog1.Color = label10.ForeColor;
            fontDialog1.Font = Properties.Settings.Default.TableFontFS;
            if (fontDialog1.ShowDialog() != System.Windows.Forms.DialogResult.Cancel)
            {
                label10.ForeColor = fontDialog1.Color;
                Properties.Settings.Default.TableTextColor = fontDialog1.Color;
                Properties.Settings.Default.TableFontFS = fontDialog1.Font;
            }
        }

        /// <summary>
        /// EPG highlighted text
        /// </summary>
        private void panel7_MouseDown(object sender, MouseEventArgs e)
        {
            fontDialog1.ShowColor = true;
            fontDialog1.Color = label26.ForeColor;
            fontDialog1.Font = Properties.Settings.Default.EPGHighFont;
            //fontDialog1.Color = Color.Blue;
            if (fontDialog1.ShowDialog() != System.Windows.Forms.DialogResult.Cancel)
            {
                panel7.BackColor = panel3.BackColor;
                label26.ForeColor = fontDialog1.Color;
                Properties.Settings.Default.EPGHighTextColor=fontDialog1.Color;
                Properties.Settings.Default.EPGHighFont = fontDialog1.Font;
            }
        }

        private void button12_Click(object sender, EventArgs e)
        {
            saveSettings();
        }

        /// <summary>
        /// Sidebar background
        /// </summary>
        private void panel9_MouseDown(object sender, MouseEventArgs e)
        {
            colorDialog1.Color = panel9.BackColor;
            if (colorDialog1.ShowDialog() != DialogResult.Cancel)
            {
                panel9.BackColor = colorDialog1.Color;
                panel10.BackColor =  colorDialog1.Color;
                Properties.Settings.Default.SideBarBackColor = colorDialog1.Color;
            }
        }
       
        /// <summary>
        /// Sidebar font
        /// </summary>
        private void panel10_MouseDown(object sender, MouseEventArgs e)
        {
            fontDialog1.ShowColor = true;
            fontDialog1.Color = label37.ForeColor;
            fontDialog1.Font = Properties.Settings.Default.SidebarFont;
            //fontDialog1.Color = Color.Blue;
            if (fontDialog1.ShowDialog() != System.Windows.Forms.DialogResult.Cancel)
            {
                panel10.BackColor = panel9.BackColor;
                label37.ForeColor = fontDialog1.Color;
                Properties.Settings.Default.SidebarFontColor = fontDialog1.Color;
                Properties.Settings.Default.SidebarFont = fontDialog1.Font;
            }
        }

        private void button13_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button14_Click(object sender, EventArgs e)
        {
            EpgForm sf = new EpgForm();
            sf.ShowDialog();
        }

        private void m3uVLCToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog1.CheckPathExists = true;
            saveFileDialog1.Filter = "m3u|*.m3u|All Files|*.*";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.DefaultExt = "m3u";
            saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                ExportToM3U.Start(saveFileDialog1.FileName);
            }
        }

        private void atvlistAditeyaTvToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog2.CheckPathExists = true;
            saveFileDialog2.Filter = "atvlist|*.atvlist|All Files|*.*";
            saveFileDialog2.FilterIndex = 1;
            saveFileDialog2.DefaultExt = "atvlist";
            saveFileDialog2.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            if (saveFileDialog2.ShowDialog() == DialogResult.OK)
            {
                ExportToAtvlist.Start(saveFileDialog2.FileName);
            }
        }

        private void csvToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog1.CheckPathExists = true;
            saveFileDialog1.Filter = "csv|*.csv|All Files|*.*";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.DefaultExt = "csv";
            saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                ExportToCSV csv = new ExportToCSV();
                csv.Start(saveFileDialog1.FileName);
            }
        }

        private void PreferencesForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!error)
            {
                saveSettings();
                if (savechannels)
                    ChannelTable.menu.Tables["Menu"].WriteXml(AppPath + @"\..\channellist.xml");
            }
        }

        /// <summary>
        /// Populate key shortcuts DataTable
        /// TODO: Use MLmessages.resx for translation. 
        /// </summary>
        private void populatekeyShortCuts()
        {
            ksd = new DataTable();
           
            DataColumn DescDc = new DataColumn();
            DescDc.ColumnName = "desc";
            DescDc.DataType = System.Type.GetType("System.String");
            DataColumn KeyDC = new DataColumn();
            KeyDC.ColumnName = "key";
            KeyDC.DataType = typeof(Keys);
        
            ksd.Columns.Add(DescDc);
            ksd.Columns.Add(KeyDC);
            
            DataRow drAR = ksd.NewRow();
            if (Properties.Settings.Default.language=="Slovenian")
                drAR["desc"] = "Razmerje slike";
            else
                drAR["desc"] = "Aspect ratio";
            drAR["key"] = Properties.Settings.Default.KeyAR;
            
            DataRow drCrop = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drCrop["desc"] = "Zoom/Maska/Vertikalna pozicija";
            else
                drCrop["desc"] = "Zoom/Mask/Vertical position";
            drCrop["key"] = Properties.Settings.Default.KeyPictSet;

            DataRow drDOWN = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drDOWN["desc"] = "Kanal dol";
            else
                drDOWN["desc"] = "Channel down";
            drDOWN["key"] = Properties.Settings.Default.KeyDOWN;

            DataRow drFull = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drFull["desc"] = "Celozaslonski način";
            else
                drFull["desc"] = "Full screen";
             drFull["key"]=Properties.Settings.Default.KeyFullScreen;

             DataRow drLEFT = ksd.NewRow();
             if (Properties.Settings.Default.language == "Slovenian")
                 drLEFT["desc"] = "Zmanjšaj glasnost";
             else
                 drLEFT["desc"] = "Volume down";
             drLEFT["key"] = Properties.Settings.Default.KeyLEFT;

             DataRow drMin = ksd.NewRow();
             if (Properties.Settings.Default.language == "Slovenian")
                 drMin["desc"] = "Minimalni način";
             else
                 drMin["desc"] = "Minimal view";
             drMin["key"] = Properties.Settings.Default.KeyMinimal;

             DataRow drMute = ksd.NewRow();
             if (Properties.Settings.Default.language == "Slovenian")
                 drMute["desc"] = "Brez zvoka";
             else
                 drMute["desc"] = "Mute";
             drMute["key"] = Properties.Settings.Default.KeyMute;

             DataRow drPause = ksd.NewRow();
             if (Properties.Settings.Default.language == "Slovenian")
                 drPause["desc"] = "Pavza";
             else
                 drPause["desc"] = "Pause";
             drPause["key"] = Properties.Settings.Default.KeyPause;

             DataRow drRec = ksd.NewRow();
             if (Properties.Settings.Default.language == "Slovenian")
                 drRec["desc"] = "Snemaj";
             else
                 drRec["desc"] = "Record";
             drRec["key"] = Properties.Settings.Default.KeyRec;

             DataRow drRight = ksd.NewRow();
             if (Properties.Settings.Default.language == "Slovenian")
                 drRight["desc"] = "Povečaj glasnost";
             else
                 drRight["desc"] = "Volume up";
             drRight["key"] = Properties.Settings.Default.KeyRIGHT;

            DataRow drSnapshot = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drSnapshot["desc"] = "Zajem slike";
            else
                drSnapshot["desc"] = "Snapshot";
            drSnapshot["key"] = Properties.Settings.Default.KeySnapshot;

            DataRow drTable = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drTable["desc"] = "Tabela";
            else
                drTable["desc"] = "Channel Table";
            drTable["key"] = Properties.Settings.Default.KeyTable;

            DataRow drUp = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drUp["desc"] = "Kanal gor";
            else
                drUp["desc"] = "Channel up";
            drUp["key"] = Properties.Settings.Default.KeyUP;

            DataRow drRecall = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drRecall["desc"] = "Prejšni izbrani kanal / PIP kanal";
            else
                drRecall["desc"] = "Previous selected channel / PIP channel";
            drRecall["key"] = Properties.Settings.Default.KeyRecall;

            DataRow drFaster = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drFaster["desc"] = "Predvajaj hitreje (TimeShift)";
            else
                drFaster["desc"] = "Play faster (Timeshift)";
            drFaster["key"] = Properties.Settings.Default.KeyFaster;

            DataRow drSlower = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drSlower["desc"] = "Predvajaj počasneje (TimeShift)";
            else
                drSlower["desc"] = "Play slower (TimeShift)";
            drSlower["key"] = Properties.Settings.Default.KeySlower;

            DataRow drOsd = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drOsd["desc"] = "Prikaži ime trenutnega kanala (OSD)";
            else
                drOsd["desc"] = "Show current channel name (OSD)";
            drOsd["key"] = Properties.Settings.Default.KeyOSD;

            DataRow drLang = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drLang["desc"] = "Audio sled";
            else
                drLang["desc"] = "Audio track";
            drLang["key"] = Properties.Settings.Default.KeyLanguage;

            DataRow drDailyEpg = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drDailyEpg["desc"] = "Dnevni epg";
            else
                drDailyEpg["desc"] = "Daily epg (plugin)";
            drDailyEpg["key"] = Properties.Settings.Default.KeyEPG;

            DataRow drPip = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drPip["desc"] = "Slika v sliki";
            else
                drPip["desc"] = "Picture in picture";
            drPip["key"] = Properties.Settings.Default.KeyPip;

            DataRow drSubs = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drSubs["desc"] = "Podnapisi";
            else
                drSubs["desc"] = "Subtitles";
            drSubs["key"] = Properties.Settings.Default.KeySubtitles;

            DataRow drTtx = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drTtx["desc"] = "Teletext";
            else
                drTtx["desc"] = "Teletext";
            drTtx["key"] = Properties.Settings.Default.KeyTeletext;

            DataRow drNormView = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drNormView["desc"] = "Normalni pogled";
            else
                drNormView["desc"] = "Normal view";
            drNormView["key"] = Properties.Settings.Default.KeyNormalView;

            DataRow drExit = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drExit["desc"] = "Izhod";
            else
                drExit["desc"] = "Exit";
            drExit["key"] = Properties.Settings.Default.KeyQuit;

            DataRow drMinimize = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drMinimize["desc"] = "Minimiraj";
            else
                drMinimize["desc"] = "Minimize";
            drMinimize["key"] = Properties.Settings.Default.KeyMinimize;

            DataRow drToTray = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drToTray["desc"] = "Minimiraj v sistemsko vrstico";
            else
                drToTray["desc"] = "Minimize to tray";
            drToTray["key"] = Properties.Settings.Default.KeyToTray;

            DataRow drSurf = ksd.NewRow();
            if (Properties.Settings.Default.language == "Slovenian")
                drSurf["desc"] = "Surf (8s)";
            else
                drSurf["desc"] = "Channel surf (8s)";
            drSurf["key"] = Properties.Settings.Default.KeySurf;

            ksd.Rows.Add(drUp);
            ksd.Rows.Add(drDOWN);
            ksd.Rows.Add(drLEFT);
            ksd.Rows.Add(drRight); 
            ksd.Rows.Add(drMute);
            ksd.Rows.Add(drAR);
            ksd.Rows.Add(drCrop);
            ksd.Rows.Add(drFull);
            ksd.Rows.Add(drMin); 
            ksd.Rows.Add(drPause);
            ksd.Rows.Add(drRecall);
            ksd.Rows.Add(drRec);
            ksd.Rows.Add(drSnapshot);
            ksd.Rows.Add(drTable); 
            ksd.Rows.Add(drFaster);
            ksd.Rows.Add(drSlower);
            ksd.Rows.Add(drOsd);
            ksd.Rows.Add(drLang);
            ksd.Rows.Add(drDailyEpg);
            ksd.Rows.Add(drPip);
            ksd.Rows.Add(drSubs);
            ksd.Rows.Add(drTtx);
            ksd.Rows.Add(drNormView); //22
            ksd.Rows.Add(drExit);     //23
            ksd.Rows.Add(drMinimize); //24
            ksd.Rows.Add(drToTray);    //25
            ksd.Rows.Add(drSurf);      //26
                      
            dataGridView2.Columns[0].DataPropertyName = "desc";
            dataGridView2.Columns[1].DataPropertyName = "key";
            dataGridView2.DataSource = ksd;
            dataGridView2.KeyDown+=new KeyEventHandler(dataGridView2_KeyDown);
            dataGridView2.SelectionMode = DataGridViewSelectionMode.CellSelect;
        }

        private void dataGridView2_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.Modifiers == Keys.Shift || e.Modifiers == Keys.Control || e.Modifiers == Keys.Alt ) && (e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.ControlKey || e.KeyCode == Keys.Menu ))
                return;

            if (dataGridView2.SelectedCells.Count>0 && dataGridView2.SelectedCells[0].ColumnIndex == 1)
            {
                bool allready = false;
                // warn if key is allready mapped
                foreach (DataRow drv in ksd.Rows)
                {
                    Keys k = (Keys)drv[1];
                    if ( k == e.KeyData)
                    {
                        if (Properties.Settings.Default.language=="Slovenian")
                             MessageBox.Show("Ta tipka je že uporabljena.");
                        else
                             MessageBox.Show("This key is allready mapped.");
                        allready = true;
                        break;
                    }
                }
                if (!allready)
                dataGridView2.SelectedCells[0].Value = e.KeyData; 
            }
        }

        /// <summary>
        /// Save key shortcuts from Datatable
        /// </summary>
        private void updateShortcuts()
        {
            Properties.Settings.Default.KeyUP = (Keys)ksd.Rows[0]["key"];
            Properties.Settings.Default.KeyDOWN = (Keys)ksd.Rows[1]["key"];
            Properties.Settings.Default.KeyLEFT = (Keys)ksd.Rows[2]["key"];
            Properties.Settings.Default.KeyRIGHT = (Keys)ksd.Rows[3]["key"];
            Properties.Settings.Default.KeyMute = (Keys)ksd.Rows[4]["key"];
            Properties.Settings.Default.KeyAR = (Keys)ksd.Rows[5]["key"];
            Properties.Settings.Default.KeyPictSet = (Keys)ksd.Rows[6]["key"];
            Properties.Settings.Default.KeyFullScreen = (Keys)ksd.Rows[7]["key"];
            Properties.Settings.Default.KeyMinimal = (Keys)ksd.Rows[8]["key"];
            Properties.Settings.Default.KeyPause = (Keys)ksd.Rows[9]["key"];
            Properties.Settings.Default.KeyRecall = (Keys)ksd.Rows[10]["key"];
            Properties.Settings.Default.KeyRec = (Keys)ksd.Rows[11]["key"];
            Properties.Settings.Default.KeySnapshot = (Keys)ksd.Rows[12]["key"];
            Properties.Settings.Default.KeyTable =  (Keys)ksd.Rows[13]["key"];
            Properties.Settings.Default.KeyFaster = (Keys)ksd.Rows[14]["key"];
            Properties.Settings.Default.KeySlower = (Keys)ksd.Rows[15]["key"];
            Properties.Settings.Default.KeyOSD = (Keys)ksd.Rows[16]["key"];
            Properties.Settings.Default.KeyLanguage = (Keys)ksd.Rows[17]["key"];
            Properties.Settings.Default.KeyEPG = (Keys)ksd.Rows[18]["key"];
            Properties.Settings.Default.KeyPip = (Keys)ksd.Rows[19]["key"];
            Properties.Settings.Default.KeySubtitles = (Keys)ksd.Rows[20]["key"];
            Properties.Settings.Default.KeyTeletext = (Keys)ksd.Rows[21]["key"];
            Properties.Settings.Default.KeyNormalView = (Keys) ksd.Rows[22]["key"];
            Properties.Settings.Default.KeyQuit = (Keys) ksd.Rows[23]["key"];
            Properties.Settings.Default.KeyMinimize = (Keys) ksd.Rows[24]["key"];
            Properties.Settings.Default.KeyToTray = (Keys)ksd.Rows[25]["Key"];
            Properties.Settings.Default.KeySurf = (Keys) ksd.Rows[26]["Key"];
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Shortcuts scForm= new Shortcuts();
            scForm.Show();
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewRow drw in dataGridView1.SelectedRows)
                {
                    if (drw.IsNewRow != true)
                        dataGridView1.Rows.Remove(drw);
                }
            }
            catch { }
        }

        private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            dataGridView1.Rows[e.RowIndex].ErrorText = "";
            int newInteger;

            // Don't try to validate the 'new row' until finished 
            // editing since there
            // is not any point in validating its initial value.
            if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }

            if (e.ColumnIndex == 1)
            {
                if (!int.TryParse(e.FormattedValue.ToString(),
                    out newInteger) || newInteger < 0)
                {
                    //this.dataGridView1.Enabled = false;
                    if (Properties.Settings.Default.language=="Slovenian")
                        MessageBox.Show("Vrednost mora biti številka.");
                    else
                         MessageBox.Show("Value has to be an integer.");
                    e.Cancel = true;
                }
            }

            if (e.RowIndex > -1 && e.ColumnIndex == 8 && dataGridView1.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn)
            {
                // No password is set or it is allready unlocked.
                if (PasswordEncription.Password == "" || PasswordEncription.Unlocked == true)
                {
                    return;
                }

                // Calculate position for password window.
                Point InputPos = Cursor.Position;
                InputPos.X = InputPos.X - 180;
                InputPos.Y = InputPos.Y - 52;

                Check ch = new Check(false);
                Password PassCheck = new Password(ch, InputPos);
                if (!PasswordEncription.Unlocked)
                    PassCheck.ShowDialog();
                if (ch.correct)
                {
                    PasswordEncription.Unlocked = true;
                }
                else
                {
                    dataGridView1.CancelEdit();
                    PasswordEncription.Unlocked = false;
                }
            }
        }

        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)
        {
            if (anError.Context == DataGridViewDataErrorContexts.Commit)
            {
                // Most propably an ip duplicate.
                
                // TODO: Mlmessages.resx
                if (Properties.Settings.Default.language=="Slovenian")
                     MessageBox.Show("Napaka. Ip že obstaja ");
                else
                     MessageBox.Show("Error. Ip allready exists.");
            }
            if (anError.Context == DataGridViewDataErrorContexts.CurrentCellChange)
            {
             
            }
            if (anError.Context == DataGridViewDataErrorContexts.Parsing)
            {
               
            }
            if (anError.Context == DataGridViewDataErrorContexts.LeaveControl)
            {
              
            }
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            savechannels = true;
        }

        private void checkBox5_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox5.CheckState == CheckState.Checked)
            {
                if (comboBox3.SelectedItem.ToString() != "Slovenian")
                    comboBox2.ForeColor = Color.Gray;
                else
                    comboBox2.ForeColor = Color.Black;
                checkBox7.CheckState = CheckState.Checked;
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            //This simply deletes user settings
            Properties.Settings.Default.Reset();
            Properties.Settings.Default.UpgradeSettings = false;
            reload();
        }

        private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
             Interfaces intf = new Interfaces();
             if (formloaded)
             {
                 try
                 {
                     string name = comboBox1.SelectedItem.ToString();
                     string ip = intf.getIpFromName(name);
                     int indx = intf.getIndexFromName(name);
                     label39.Text = ip + " {" + indx + "}";
                 }
                 catch
                 {
                     try
                     {
                         label39.Text = "N/A";
                     }
                     catch { }
                 }
             }
        }

        private void button15_Click(object sender, EventArgs e)
        {
            PictureSettings ps = new PictureSettings();
            ps.Show();
            //
            vlcInitNeeded = true;
        }

        private void button16_Click(object sender, EventArgs e)
        {
            OsdSettings os = new OsdSettings();
            os.Show();
        }

        private void button17_Click(object sender, EventArgs e)
        {
            ChannelTableSettings cts = new ChannelTableSettings();
            cts.Show();
        }

        private void comboBox2_SelectionChangeCommitted(object sender, EventArgs e)
        {
            Types.AvailablePlugin selectedPlugin = GlobalP.Plugins.AvailablePlugins.Find((string)comboBox2.SelectedItem);
            if (selectedPlugin != null)
            { 
                Properties.Settings.Default.EPGPlugin= (string)comboBox2.SelectedItem;
                // plugin selected
                // if epg is null, initialize it.
                parent.epg = null;
                parent.Invoke(new delegateParentThread(parent.enableEpg));
                if (comboBox2.SelectedIndex == -1)
                    button14.Enabled = false;
                else
                    button14.Enabled = true;
            }
        }

        /// <summary>
        /// Generate udpRelay playlist
        /// </summary>
        private void button18_Click(object sender, EventArgs e)
        {
            saveFileDialog1.CheckPathExists = true;
            saveFileDialog1.Filter = "txt|*.txt|All Files|*.*";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.DefaultExt = "txt";
            saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            saveFileDialog1.FileName = saveFileDialog1.InitialDirectory + @"\channels.txt";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                ExportToM3UUdpRelay ur = new ExportToM3UUdpRelay();
                ur.Start(saveFileDialog1.FileName);
            }
        }

        private void checkBox15_Click(object sender, EventArgs e)
        {
            if (checkBox16.CheckState == CheckState.Checked)
            {
                checkBox16.CheckState = CheckState.Unchecked;
            }
            checkBox15.CheckState = CheckState.Checked;
            Properties.Settings.Default.UnicastServer = "vlc";
        }

        private void checkBox16_Click(object sender, EventArgs e)
        {
            if (checkBox15.CheckState == CheckState.Checked)
            {
                checkBox15.CheckState = CheckState.Unchecked;
            }
            checkBox16.CheckState = CheckState.Checked;
            Properties.Settings.Default.UnicastServer = "udprelay";
        }

        private void checkBox79_Click(object sender, EventArgs e)
        {
            uncheckCardSelectionCB();
            checkBox79.CheckState = CheckState.Checked;
            //
            vlcInitNeeded = true;
        }

        private void checkBox80_Click(object sender, EventArgs e)
        {
           uncheckCardSelectionCB();
           checkBox80.CheckState = CheckState.Checked;
            //
           vlcInitNeeded = true;
        }

        private void checkBox81_Click(object sender, EventArgs e)
        {
           uncheckCardSelectionCB();
           checkBox81.CheckState = CheckState.Checked;
            //
           vlcInitNeeded = true;
        }

        private void uncheckCardSelectionCB()
        {
            checkBox79.CheckState = CheckState.Unchecked;
            checkBox80.CheckState = CheckState.Unchecked;
            checkBox81.CheckState = CheckState.Unchecked;
        }

        private void swapWithRow(bool up)
        {
            if (dataGridView1.SortedColumn != dataGridView1.Columns[1])
                dataGridView1.Sort(dataGridView1.Columns[1], ListSortDirection.Ascending);

            if (dataGridView1.SelectedRows.Count > 0)
            {
                DataGridViewRow current = dataGridView1.SelectedRows[0];
                int i = 0;
                if (up && current.Index + 1 < dataGridView1.Rows.Count - 1)
                    i = 1;
                else if (!up && current.Index - 1 >= 0)
                    i = -1;
                
                DataGridViewRow next = dataGridView1.Rows[current.Index + i];
                int curChan = (int)current.Cells[1].Value;
                int nextChan = (int) next.Cells[1].Value;
                
                 // swap it
                if ( ( up && ((nextChan > curChan) && !current.Equals(next)) ) ||  ( !up && ((nextChan < curChan) && !current.Equals(next)) ) )
                {
                    ChannelTable.menu.Tables["Menu"].BeginLoadData();
                    ((DataRowView)current.DataBoundItem)[1]= nextChan;
                    ((DataRowView)next.DataBoundItem)[1] = curChan;
                    ChannelTable.menu.Tables["Menu"].EndLoadData();
                    
                    dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.IndexOf(next)].Cells[1];
                    next.Selected = true;
                }
            }
       }

        private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && e.RowIndex >= 0)
            {
                if (dataGridView1.SelectedRows.Count <= 1)
                {
                    dataGridView1.Rows[e.RowIndex].Selected = true;
                    dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[1];
                }
                    contextMenuStrip2.Show(Cursor.Position);
            }
        }
        //up 1
        private void moveDownToolStripMenuItem_Click(object sender, EventArgs e)
        {
            addNum(1);
        }
        //down
        private void moveUpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            addNum(-1);
        }

        // FIXME: To slow!!
        private void addNum(int n)
        {
            if (dataGridView1.SortedColumn != dataGridView1.Columns[1])
                dataGridView1.Sort(dataGridView1.Columns[1], ListSortDirection.Ascending);

            // all from selected on
            if (dataGridView1.SelectedRows.Count <= 1)
            {
                DataGridViewCell currentcell = dataGridView1.CurrentCell;
                 
                int start = dataGridView1.CurrentCell.RowIndex;
                int stop = dataGridView1.Rows.Count - 1;

                ChannelTable.menu.Tables["Menu"].BeginLoadData();
                List<DataRowView> after = new List<DataRowView>();
                for (int i = start; i < stop; i++)
                {
                    DataRowView dwt = (DataRowView)dataGridView1.Rows[i].DataBoundItem;
                    after.Add(dwt);
                }
                foreach (DataRowView dwt in after)
                {
                    dwt.Row[1] = Math.Max(0,(int)dwt.Row[1] + n);
                }
                ChannelTable.menu.Tables["Menu"].EndLoadData();

                if (currentcell.RowIndex >= 0)
                    dataGridView1.CurrentCell = currentcell;

            }
            // only selected
            else if (dataGridView1.SelectedRows.Count > 1)
            {
                int[] indexes = { 0 };
                int i = 0;
                ChannelTable.menu.Tables["Menu"].BeginLoadData();
                foreach (DataGridViewRow dw in dataGridView1.SelectedRows)
                {
                    indexes[i] = dw.Index;
                    DataRowView dwt = (DataRowView)dw.DataBoundItem;
                    if (dwt != null && !dwt.IsNew)
                        dwt.Row[1] = Math.Max(0,(int)dwt.Row[1] + n);
                }
                ChannelTable.menu.Tables["Menu"].EndLoadData();
            }
        }

        private void moveUpToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            swapWithRow(false);
        }

        private void moveDownToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            swapWithRow(true);
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            recOptions();
        }
        private void recOptions()
        { 
             if (checkBox2.CheckState == CheckState.Checked)
            {
                comboBox8.Enabled = false;
            }
            else
            {
                comboBox8.Enabled = true;
            }
        }

        private void button19_Click(object sender, EventArgs e)
        {
            ChannelSettings.List.Clear();
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            addNum(+10);
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            addNum(-10);
        }

        // vlc reload needed
        private void comboBox4_SelectionChangeCommitted(object sender, EventArgs e)
        {
            //deinterlace
            vlcInitNeeded = true; 
        }

        private void numericUpDown9_ValueChanged(object sender, EventArgs e)
        {
           // skiploop
           vlcInitNeeded = true; 
        }

        private void numericUpDown9_MouseClick(object sender, MouseEventArgs e)
        {
           // skiploop
           vlcInitNeeded = true; 
        }

        private void checkBox3_MouseClick(object sender, MouseEventArgs e)
        {
           // hardware yuv
           vlcInitNeeded = true; 
        }

        private void comboBox6_SelectionChangeCommitted(object sender, EventArgs e)
        {
            // renderer
           vlcInitNeeded = true;
           restartNeeded = true;
        }

        private void comboBox7_SelectionChangeCommitted(object sender, EventArgs e)
        {
            // adio connect to
           vlcInitNeeded = true;
        }

        private void comboBox9_SelectionChangeCommitted(object sender, EventArgs e)
        {
            // audio pro-logic
            vlcInitNeeded = true;
        }

        private void numericUpDown10_MouseClick(object sender, MouseEventArgs e)
        {
            // audio sync
            vlcInitNeeded = true;
        }

        private void checkBox11_Click(object sender, EventArgs e)
        {
            // spdif
            vlcInitNeeded = true;
        }

        private void checkBox12_Click(object sender, EventArgs e)
        {
            // normalize
            vlcInitNeeded = true;
        }

        private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
        {
            // interface changed
            vlcInitNeeded = true;
        }

        private void maskedTextBox1_Validating(object sender, CancelEventArgs e)
        {
            // first time change
            if (PasswordEncription.Password == "")
            {
                PasswordEncription.Password = maskedTextBox1.Text;
                PasswordEncription.encrypt();
            }
            else
            {
                // calculate position for password window
                Point InputPos = maskedTextBox1.PointToScreen(new Point(0, 0));
                InputPos.Y = Math.Max(0, InputPos.Y - 104);
                
                //user changed password, let's ask him or her :) for correct password 
                Check ch = new Check(false);
                Password PassCheck = new Password(ch,InputPos);
                PassCheck.ShowDialog();
                if (ch.correct)
                {
                    //password is correct - save new passord
                    PasswordEncription.Password = maskedTextBox1.Text;
                    PasswordEncription.encrypt();
                }
            }
        }

        private void button7_Click_1(object sender, EventArgs e)
        {
            Report rp = new Report();
            rp.ShowDialog();
        }

        private void m3uTanoPlayerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TanoExport te = new TanoExport();
            te.ShowDialog();
        }
    }

    public class Check
    {
        bool c;
        public Check(bool input)
        {
            c = input;
        }
        public Check()
        { 
        
        }
        public bool correct
        {
            get { return c;}
            set { c = value; }
        }
    }
}
